<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>完整日志上传测试</title>
    <style>
        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
            max-width: 800px;
            margin: 0 auto;
            padding: 20px;
            line-height: 1.6;
        }
        h1 {
            color: #333;
            text-align: center;
        }
        .container {
            background-color: #f5f5f5;
            padding: 20px;
            border-radius: 8px;
            margin: 20px 0;
        }
        button {
            background-color: #4CAF50;
            color: white;
            padding: 10px 20px;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            margin-right: 10px;
            margin-bottom: 10px;
        }
        button:hover {
            background-color: #45a049;
        }
        .error-btn {
            background-color: #f44336;
        }
        .error-btn:hover {
            background-color: #d32f2f;
        }
        .warning-btn {
            background-color: #ff9800;
        }
        .warning-btn:hover {
            background-color: #e68900;
        }
        input[type="text"], input[type="password"] {
            padding: 10px;
            width: 100%;
            margin-bottom: 10px;
            border: 1px solid #ddd;
            border-radius: 4px;
            box-sizing: border-box;
        }
        .result {
            margin-top: 20px;
            padding: 10px;
            background-color: #fff;
            border: 1px solid #ddd;
            border-radius: 4px;
            max-height: 300px;
            overflow-y: auto;
        }
        .success {
            color: green;
        }
        .error {
            color: red;
        }
        .warning {
            color: orange;
        }
        .info {
            color: blue;
        }
        .log-item {
            padding: 5px;
            border-bottom: 1px solid #eee;
        }
        .log-item:last-child {
            border-bottom: none;
        }
        .tabs {
            display: flex;
            margin-bottom: 20px;
        }
        .tab {
            padding: 10px 20px;
            background-color: #ddd;
            cursor: pointer;
            border-right: 1px solid #bbb;
        }
        .tab.active {
            background-color: #4CAF50;
            color: white;
        }
        .tab-content {
            display: none;
        }
        .tab-content.active {
            display: block;
        }
        .clear-btn {
            background-color: #666;
        }
        .clear-btn:hover {
            background-color: #555;
        }
        .debug-info {
            font-size: 12px;
            color: #666;
            margin-top: 10px;
        }
    </style>
</head>
<body>
    <h1>完整日志上传测试</h1>
    
    <div class="container">
        <div class="tabs">
            <div class="tab active" onclick="openTab(event, 'login')">登录</div>
            <div class="tab" onclick="openTab(event, 'logUpload')">日志上传</div>
            <div class="tab" onclick="openTab(event, 'debugInfo')">调试信息</div>
        </div>
        
        <!-- 登录表单 -->
        <div id="login" class="tab-content active">
            <h2>用户登录</h2>
            <p>请先登录以获取认证令牌，然后才能上传日志</p>
            
            <div>
                <label for="username">用户名：</label>
                <input type="text" id="username" value="admin" placeholder="请输入用户名">
            </div>
            
            <div>
                <label for="password">密码：</label>
                <input type="password" id="password" value="123456" placeholder="请输入密码">
            </div>
            
            <button id="loginBtn">登录</button>
            <button id="logoutBtn" class="error-btn" disabled>退出登录</button>
            
            <div id="loginResult" class="result">
                登录状态将显示在这里...
            </div>
        </div>
        
        <!-- 日志上传表单 -->
        <div id="logUpload" class="tab-content">
            <h2>日志上传测试</h2>
            
            <div>
                <button id="addInfoLog" class="success-btn">添加INFO日志</button>
                <button id="addWarnLog" class="warning-btn">添加WARN日志</button>
                <button id="addErrorLog" class="error-btn">添加ERROR日志</button>
                <button id="clearLogs" class="clear-btn">清空日志</button>
            </div>
            
            <div>
                <button id="testUploadBtn" disabled>测试日志上传</button>
            </div>
            
            <div>
                <h3>待上传日志</h3>
                <div id="logsContainer" class="result">
                    暂无日志
                </div>
            </div>
            
            <div>
                <h3>上传结果</h3>
                <div id="uploadResult" class="result">
                    上传结果将显示在这里...
                </div>
            </div>
        </div>
        
        <!-- 调试信息 -->
        <div id="debugInfo" class="tab-content">
            <h2>调试信息</h2>
            
            <div>
                <h3>Token信息</h3>
                <div id="tokenInfo" class="result">
                    token信息将显示在这里...
                </div>
            </div>
            
            <div>
                <h3>网络请求日志</h3>
                <div id="networkLogs" class="result">
                    网络请求日志将显示在这里...
                </div>
            </div>
        </div>
    </div>

    <script>
        // 全局变量
        let logs = [];
        let isLoggedIn = false;
        let token = null;
        
        // DOM元素
        const loginBtn = document.getElementById('loginBtn');
        const logoutBtn = document.getElementById('logoutBtn');
        const testUploadBtn = document.getElementById('testUploadBtn');
        const loginResult = document.getElementById('loginResult');
        const logsContainer = document.getElementById('logsContainer');
        const uploadResult = document.getElementById('uploadResult');
        const tokenInfo = document.getElementById('tokenInfo');
        const networkLogs = document.getElementById('networkLogs');
        
        // 显示结果
        function showResult(element, message, type = 'info') {
            const typeClass = type === 'success' ? 'success' : type === 'error' ? 'error' : type === 'warning' ? 'warning' : 'info';
            element.innerHTML = `<p class="${typeClass}">${message}</p>`;
        }
        
        // 添加日志到容器
        function addLogToContainer(log) {
            logs.push(log);
            updateLogsContainer();
        }
        
        // 更新日志容器显示
        function updateLogsContainer() {
            if (logs.length === 0) {
                logsContainer.innerHTML = '暂无日志';
                return;
            }
            
            logsContainer.innerHTML = '';
            logs.forEach((log, index) => {
                const logItem = document.createElement('div');
                logItem.className = 'log-item';
                
                const levelClass = log.level === 'INFO' ? 'success' : log.level === 'WARN' ? 'warning' : 'error';
                
                logItem.innerHTML = `
                    <p><strong>[${log.level}] [${new Date(log.timestamp).toLocaleString()}]</strong> ${log.message}</p>
                    <p class="debug-info">模块: ${log.module || 'unknown'}</p>
                `;
                
                logsContainer.appendChild(logItem);
            });
        }
        
        // 添加网络请求日志
        function addNetworkLog(message) {
            const logItem = document.createElement('div');
            logItem.className = 'log-item';
            logItem.innerHTML = `
                <p><strong>[${new Date().toLocaleTimeString()}]</strong> ${message}</p>
            `;
            
            networkLogs.appendChild(logItem);
            networkLogs.scrollTop = networkLogs.scrollHeight;
        }
        
        // 清空所有日志
        function clearAllLogs() {
            logs = [];
            updateLogsContainer();
            showResult(uploadResult, '上传结果将显示在这里...');
        }
        
        // 切换标签页
        function openTab(evt, tabName) {
            // 隐藏所有内容
            const tabContents = document.getElementsByClassName('tab-content');
            for (let i = 0; i < tabContents.length; i++) {
                tabContents[i].classList.remove('active');
            }
            
            // 移除所有标签的active状态
            const tabs = document.getElementsByClassName('tab');
            for (let i = 0; i < tabs.length; i++) {
                tabs[i].classList.remove('active');
            }
            
            // 显示选中的标签内容
            document.getElementById(tabName).classList.add('active');
            evt.currentTarget.classList.add('active');
        }
        
        // 登录功能
        function login() {
            const username = document.getElementById('username').value;
            const password = document.getElementById('password').value;
            
            if (!username || !password) {
                showResult(loginResult, '用户名和密码不能为空！', 'error');
                return;
            }
            
            showResult(loginResult, '正在登录...');
            addNetworkLog(`正在向 /auth/login 发送登录请求`);
            
            fetch('http://localhost:8080/auth/login', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({
                    username: username,
                    password: password
                })
            })
            .then(response => {
                addNetworkLog(`登录请求返回状态码: ${response.status}`);
                return response.json().then(data => ({ status: response.status, data }));
            })
            .then(({ status, data }) => {
                if (status === 200 && data.token) {
                    isLoggedIn = true;
                    token = data.token;
                    
                    // 保存token到localStorage
                    localStorage.setItem('token', token);
                    
                    showResult(loginResult, `登录成功！欢迎 ${username}`, 'success');
                    logoutBtn.disabled = false;
                    testUploadBtn.disabled = false;
                    
                    // 更新token信息显示
                    tokenInfo.innerHTML = `
                        <p>Token: ${token.substring(0, 20)}...${token.substring(token.length - 20)}</p>
                        <p>Token长度: ${token.length} 字符</p>
                        <p>Token点数量: ${(token.match(/\./g) || []).length}</p>
                        <p>已保存到localStorage</p>
                    `;
                    
                    addNetworkLog(`登录成功，已保存token`);
                } else {
                    showResult(loginResult, `登录失败: ${data.msg || '未知错误'}`, 'error');
                    addNetworkLog(`登录失败: ${data.msg || '未知错误'}`);
                }
            })
            .catch(error => {
                showResult(loginResult, `登录异常: ${error.message}`, 'error');
                addNetworkLog(`登录异常: ${error.message}`);
            });
        }
        
        // 退出登录
        function logout() {
            isLoggedIn = false;
            token = null;
            localStorage.removeItem('token');
            
            showResult(loginResult, '已退出登录', 'info');
            logoutBtn.disabled = true;
            testUploadBtn.disabled = true;
            
            tokenInfo.innerHTML = 'token信息将显示在这里...';
            addNetworkLog('已退出登录，移除token');
        }
        
        // 测试日志上传
        function testLogUpload() {
            if (!isLoggedIn || !token) {
                showResult(uploadResult, '请先登录！', 'error');
                return;
            }
            
            if (logs.length === 0) {
                showResult(uploadResult, '请先添加测试日志！', 'warning');
                return;
            }
            
            showResult(uploadResult, '正在上传日志...');
            addNetworkLog(`正在向 /api/logs/collect 发送日志上传请求`);
            
            // 构造日志数据
            const logData = {
                requestId: generateRandomId(),
                timestamp: Date.now(),
                logs: logs,
                environment: 'development',
                clientIp: '127.0.0.1',
                appVersion: '1.0.0'
            };
            
            fetch('http://localhost:8080/api/logs/collect', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'Authorization': `Bearer ${token}`
                },
                body: JSON.stringify(logData)
            })
            .then(response => {
                addNetworkLog(`日志上传请求返回状态码: ${response.status}`);
                
                if (response.ok) {
                    showResult(uploadResult, `日志上传成功！共上传 ${logs.length} 条日志`, 'success');
                    addNetworkLog(`日志上传成功，共 ${logs.length} 条`);
                } else {
                    response.json().then(data => {
                        showResult(uploadResult, `日志上传失败！状态码: ${response.status}, 错误: ${data.msg || '未知错误'}`, 'error');
                        addNetworkLog(`日志上传失败: ${response.status}, ${data.msg || '未知错误'}`);
                    }).catch(() => {
                        showResult(uploadResult, `日志上传失败！状态码: ${response.status}`, 'error');
                        addNetworkLog(`日志上传失败: ${response.status}`);
                    });
                }
            })
            .catch(error => {
                showResult(uploadResult, `日志上传异常: ${error.message}`, 'error');
                addNetworkLog(`日志上传异常: ${error.message}`);
            });
        }
        
        // 生成随机ID
        function generateRandomId() {
            return Math.random().toString(36).substring(2, 15) + Math.random().toString(36).substring(2, 15);
        }
        
        // 初始化页面
        function init() {
            // 检查localStorage中是否有token
            const storedToken = localStorage.getItem('token');
            if (storedToken) {
                token = storedToken;
                isLoggedIn = true;
                logoutBtn.disabled = false;
                testUploadBtn.disabled = false;
                
                tokenInfo.innerHTML = `
                    <p>Token: ${token.substring(0, 20)}...${token.substring(token.length - 20)}</p>
                    <p>Token长度: ${token.length} 字符</p>
                    <p>Token点数量: ${(token.match(/\./g) || []).length}</p>
                    <p>已从localStorage加载</p>
                `;
                
                showResult(loginResult, '已从localStorage恢复登录状态', 'success');
            }
            
            // 绑定事件监听器
            loginBtn.addEventListener('click', login);
            logoutBtn.addEventListener('click', logout);
            testUploadBtn.addEventListener('click', testLogUpload);
            
            // 添加不同级别的日志
            document.getElementById('addInfoLog').addEventListener('click', () => {
                addLogToContainer({
                    level: 'INFO',
                    message: '这是一条测试INFO日志，包含中文内容',
                    timestamp: Date.now(),
                    module: 'TestModule',
                    user: 'testUser'
                });
            });
            
            document.getElementById('addWarnLog').addEventListener('click', () => {
                addLogToContainer({
                    level: 'WARN',
                    message: '这是一条测试WARN日志，用于警告级别测试',
                    timestamp: Date.now(),
                    module: 'WarningModule',
                    user: 'testUser'
                });
            });
            
            document.getElementById('addErrorLog').addEventListener('click', () => {
                addLogToContainer({
                    level: 'ERROR',
                    message: '这是一条测试ERROR日志，用于错误级别测试',
                    timestamp: Date.now(),
                    module: 'ErrorModule',
                    user: 'testUser',
                    error: '测试错误信息'
                });
            });
            
            document.getElementById('clearLogs').addEventListener('click', clearAllLogs);
        }
        
        // 页面加载完成后初始化
        window.addEventListener('load', init);
    </script>
</body>
</html>